<template>
  <basic-container>
    <avue-crud
    :option="option"
    :table-loading="loading"
    :data="data"
    v-model:page="page"
    v-model:search = "search"
    :permission="permissionList"
    :before-open="beforeOpen"
    v-model="form"
    ref="crud"
    @sort-change="sortChange"
    @row-update="rowUpdate"
    @row-save="rowSave"
    @row-del="rowDel"
    @search-change="searchChange"
    @search-reset="searchReset"
    @selection-change="selectionChange"
    @current-change="currentChange"
    @size-change="sizeChange"
    @refresh-change="refreshChange"
    @on-load="onLoad">
    <template #menu-left>
        <el-button
                type="primary"
                icon="el-icon-plus"
                v-if="permission.supplier_add"
                @click="handleAdd"

        >新 增
        </el-button>
      <el-button type="danger"
                 icon="el-icon-delete"
                 v-if="permission.supplier_delete"
                 @click="handleDelete">删 除
      </el-button>
        <el-button
                type="warning"
                icon="el-icon-download"
                v-if="permission.supplier_delete"
                @click="handleExport"
        >导 出
        </el-button>
    </template>
    <template #createTime-search="{ disabled, size }">
      <div style="display: flex;flex-direction: start;">
            <el-select v-model="search.createTimeRule" placeholder="比较" filterable clearable>
              <el-option label="" value=""></el-option>
              <el-option value=">" label="大于">大于 </el-option>
              <el-option value=">=" label="大于等于">大于等于 </el-option>
              <el-option value="=" label="等于">等于 </el-option>
              <el-option value="!=" label="不等于">不等于 </el-option>
              <el-option value="<=" label="小于等于">小于等于 </el-option>
              <el-option value="<" label="小于">小于 </el-option>
            </el-select>
            <el-date-picker
                    size="default"
                    v-model="search.createTimeSearch"
                    type="date"
                    :format="dateFormat"
                    :value-format="dateFormat"
                    :unlink-panels="true"
                    clearable
                    placeholder="创建日期"
                    @change="handleDatePickerChange"
                    :picker-options="pickerOptions"
            >
            </el-date-picker>
          </div>
      </template>
      <template #menu-right="{disabled}">
        <div style="float: left; padding-right: 20px;">
          <el-radio-group v-model="search.supStatus" class="list">
            <el-radio label="有效" @change="refreshChange">有效</el-radio>
            <el-radio label="无效" @change="refreshChange">无效</el-radio>
          </el-radio-group>
        </div>
      </template>

      <template #menu="{ row, size, type }">
        <el-tooltip content="查看" placement="top">
          <el-button
                  icon="el-icon-view"
                  link
                  :size="size"
                  :type="type"
                  @click="() => handleView(row)"
                  v-if="permission.supplier_view"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="修改" placement="top">
          <el-button
                  icon="el-icon-edit"
                  link
                  :size="size"
                  :type="type"
                  @click="() => handleEdit(row)"
                  v-if="permission.supplier_edit"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="有效" placement="top" v-if="row.supStatus=='无效'">
          <el-button
                  icon="CircleCheck"
                  link
                  :size="size"
                  :type="type"
                  @click="() => handleValid(row)"
                  v-if="permission.supplier_edit"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="无效" placement="top" v-if="row.supStatus=='有效'">
          <el-button
                  icon="CircleClose"
                  link
                  :size="size"
                  :type="type"
                  @click="() => handleInvalid(row)"
                  v-if="permission.supplier_edit"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="删除" placement="top">
          <el-button
                  icon="el-icon-delete"
                  link
                  :size="size"
                  :type="type"
                  @click="() => rowDel(row)"
                  v-if="permission.supplier_delete"
          >
          </el-button>
        </el-tooltip>
      </template>
    </avue-crud>


    <supplier-form ref="supplierInfoForm" @success="refreshChange" ></supplier-form>


  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove, updateSupStatus} from "@/api/anwise/supplier";
import { mapGetters } from "vuex";
import supplierForm from "@/views/anwise/setting/supplier_form.vue";
import website from '@/config/website';
import { getToken } from '@/utils/auth';
import { exportBlob } from '@/api/common';
import { downloadXls } from '@/utils/util';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import func from '@/utils/func';
import {userCompany} from "@/api/anwise/common";
export default {
  components: {
    supplierForm,
  },
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      dateFormat: 'YYYY-MM-DD',
      pickerOptions: {},
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      search:{
        supStatus: '有效'
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: false,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
          reserveSelection:true,
        searchLabelWidth:100,
        labelWidth: 150,
          indexWidth:100,
        menuWidth: 180,
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        delBtn: false,
        stripe: true,
        searchIndex: 3,
        searchIcon: false,
          searchEnter:true,
        column: [
          // {
          //   label: "",
          //   prop: "id",
          //   type: "input",
          //   addDisplay: false,
          //   editDisplay: false,
          //   viewDisplay: false,
          //     overHidden: true,
          //     sortable: true,
          //   hide: true,
          // },
            {
                label: "供应商账号",
                prop: "supNo",
                type: "number",
                sortable: 'custom',
                overHidden: true,
                fixed:true,
                search: true,
                width: 140,
                precision:0,
                min:0,
                controls:false,
            },
          // {
          //   label: "供应商简称",
          //   prop: "supCode",
          //   type: "input",
          //   sortable: true,
          //     overHidden: true,
          //     fixed:true,
          //   // search: true,
          //   hide:true,
          //     width: 140,
          // },
          {
            label: "供应商全称",
            prop: "supName",
            type: "input",
            search: true,
              fixed:true,
            sortable: true,
              overHidden: true,
              width: 140,
            rules: [{
              required: true,
              message: "请输入供应商全称",
              trigger: "blur"
            }],
          },
            {
                label: "供应商类型",
                prop: "supType",
                type: "select",
                search: true,
                sortable: true,
                overHidden: true,
                filterable:true,
                width: 140,
                dicUrl: '/api/blade-system/dict-biz/dictionary?code=supplier_type',
                props: {
                    label: 'dictValue',
                    value: 'dictKey',
                },
                dataType: 'string',
                rules: [{
                    required: true,
                    message: "请输入供应商类型",
                    trigger: "blur"
                }],
            },
          {
            label: "供应商地址",
            prop: "supAddr",
            type: "input",
            sortable: true,
              overHidden: true,
              width: 200,
            rules: [{
              required: true,
              message: "请输入供应商地址",
              trigger: "blur"
            }],
          },
            {
                label: "结算方式",
                prop: "payType",
                type: "select",
                search: true,
                sortable: true,
                overHidden: true,
                width: 120,
                filterable:true,
                dicUrl: '/api/blade-system/dict-biz/dictionary?code=pay_type',
                props: {
                    label: 'dictValue',
                    value: 'dictKey',
                },
                dataType: 'string',
                rules: [{
                    required: true,
                    message: "请输入结算方式",
                    trigger: "blur"
                }],
            },
            {
                label: "税率",
                prop: "taxRate",
                type: "input",
                sortable: true,
                overHidden: true,
                width: 120,
                rules: [{
                    required: false,
                    message: "请输入税率",
                    trigger: "blur"
                }],
                formatter:(val,value,label)=>{
                    if (value) {
                        return `${value}%VAT`
                    } else {
                        return ''
                    }
                },
            },
            {
                label: "币别",
                prop: "rmb",
                type: "select",
                filterable: true,
                dicUrl: '/api/blade-system/dict-biz/dictionary?code=rmb',
                props: {
                    label: 'dictValue',
                    value: 'dictKey',
                },
                dataType: 'string',
                rules: [{
                    required: false,
                    message: "请输入币别",
                    trigger: "blur"
                }],
            },
            {
                label: "联系人",
                prop: "supContact",
                type: "input",
                search: true,
                sortable: true,
                overHidden: true,
                width: 120,
                rules: [{
                    required: true,
                    message: "请输入联系人",
                    trigger: "blur"
                }],
            },
          {
            label: "联系电话",
            prop: "supPhone",
              type: "number",
              precision:0,
              min:1,
              controls:false,
            search: true,
            sortable: true,
              overHidden: true,
              width: 120,
            rules: [{
              required: true,
              message: "请输入联系电话",
              trigger: "blur"
            }],
          },
          {
            label: "邮箱地址",
            prop: "supMail",
            type: "input",
            sortable: true,
              overHidden: true,
              width: 120,
          },

            // {
            //     label: "组织机构",
            //     prop: "deptId",
            //     type: "select",
            //     search: true,
            //     sortable: true,
            //     overHidden: true,
            //     width: 120,
            //     filterable: true,
            //     dicUrl: '/api/blade-anwise/common/supplierDept',
            //     props: {
            //         label: 'deptName',
            //         value: 'id',
            //     },
            //     dataType: 'string',
            //     rules: [{
            //         required: true,
            //         message: "请输入组织机构",
            //         trigger: "blur"
            //     }],
            // },
          {
            label: "归属机构",
            width: 120,
            prop: "ownId",
            type: "select",
            search: true,
            filterable: true,
              virtualize: true,
            dicUrl: '/api/blade-anwise/common/deptListFilter?deptCategory=1&bodyType=1,3',
            display:true,
            props: {
              label: 'deptName',
              value: 'id',
            },
            dataType: 'string',
            overHidden: true,
            rules: [{
              required: true,
              message: "请输入归属机构",
              trigger: "blur"
            }],
          },
          {
            label: "创建人员",
            prop: "createUserName",
            type: "input",
            sortable: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
              overHidden: true,
              width: 120,
          },
          {
            label: "创建时间",
            prop: "createTime",
            type: "input",
            sortable: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
              overHidden: true,
              width: 120,
          },
          {
            label: "是否有效",
            width: 120,
            prop: "supStatus",
            type: "select",
            filterable: true,
            dicUrl: '/api/blade-system/dict-biz/dictionary?code=is_enabled',
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
            dataType: 'string',
            // search:true,
            rules: [{
              required: false,
              message: "请选择是否有效",
              trigger: "blur"
            }],
          },
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.supplier_add, false),
        viewBtn: this.validData(this.permission.supplier_view, false),
        delBtn: this.validData(this.permission.supplier_delete, false),
        editBtn: this.validData(this.permission.supplier_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  // created() {
  //   this.search.supStatus='1';
  // },
  methods: {
    handleValid(row){
      row.supStatus = '有效'
      updateSupStatus(row).then(res=>{
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      })
    },
    handleInvalid(row){
      row.supStatus = '无效'
      updateSupStatus(row).then(res=>{
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      })
    },
    handleView(row) {
      let title = "查看供应商信息";
      let type = 'view';
      const id = row.id;
      this.$refs.supplierInfoForm.show({
        id,
        title,
        type
      })
    },
    handleEdit(row) {
      let title = "编辑供应商信息";
      let type = 'edit';
      const id = row.id;
      this.$refs.supplierInfoForm.show({
        id,
        title,
        type
      })
    },
    handleAdd() {
      userCompany().then(res => {
        if (res.data.success) {
          this.dept = res.data.data;
          if (!this.dept) {
            this.$message({
              type: "error",
              message: "用户无组织机构信息，请联系安伟工作人员！"
            });
          } else {
            let title = "创建供应商信息";
            let type = 'edit';
            this.$refs.supplierInfoForm.show({
              title,
              type
            })
          }
        }
      })
    },
      handleExport() {
          // const account = func.toStr(this.search.account);
          // const realName = func.toStr(this.search.realName);
              NProgress.start();
              exportBlob(
                  `/blade-anwise/supplier/export?${
                      this.website.tokenHeader
                      }=${getToken()}`,this.search
              ).then(res => {
                  downloadXls(res.data, `供应商数据${this.$dayjs().format('YYYYMMDDHHmmss')}.xlsx`);
                  NProgress.done();
              });
      },
    sortChange(val) {
      console.log(val)
      this.sort = {
        prop: val.prop,
        order: val.order
      };
      let order = "";
      if (this.sort.prop && this.sort.order) {
        if (this.sort.order === "descending") {
          order = `${this.sort.prop} desc`
        } else {
          order = `${this.sort.prop} asc`
        }
      }
      this.query.orderBy = order;
      this.onLoad(this.page);
    },
    rowSave(row, done, loading) {
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
      searchReset() {
          this.query = {};
          this.search.createTimeSearch = '';
          // this.search.supStatus = '';
          this.onLoad(this.page);
      },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      params.supStatus = this.search.supStatus;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handleDatePickerChange(value) {
        console.log(this.search);
    },
  }
};
</script>

<style></style>
